package org.lmind.example.common.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.lmind.example.common.web.internal.ServletContextWrapper;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

public class WebAppLoader implements Filter, ServletContextListener, ServletRequestListener, HttpSessionListener {
	
	private ContextLoader contextLoader = new ContextLoader();
	
	private WebApplicationContext wac;
	
	private VirtualFilter virtualFilter;

	public WebAppLoader() {
		
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {

	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {

	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("contextConfigLocation", "classpath:org.lmind.example.common.web.xml,classpath:spring-context.xml");
		//map.put("contextConfigLocation", "classpath:spring-context.xml");
		ServletContextWrapper wrapper = new ServletContextWrapper(filterConfig.getServletContext());
		wrapper.setInitParameters(map);
		wac = contextLoader.initWebApplicationContext(wrapper);
		
		virtualFilter = wac.getBean(VirtualFilter.class);
		Map<String, FilterChainConfiguration> m = wac.getBeansOfType(FilterChainConfiguration.class);
		for (FilterChainConfiguration chain : m.values()) {
			virtualFilter.appendFilters(chain.getFilters());
		}
		virtualFilter.init(filterConfig);
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		virtualFilter.doFilter(request, response, chain);
		//chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		virtualFilter.destroy();
	}

}
